package com.ly.exp;

import com.ly.common.Result;
import com.ly.common.StatusEnum;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
    * 自定义异常全局捕捉
    */
    @ExceptionHandler(ServiceException.class)
    public Result<?> serviceException(ServiceException e){
        return new Result<>(e.getCode(),e.getMessage());
    }
    /**
    * JSR303参数全局异常捕捉
    */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> methodArgumentNotValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        return new Result<>(StatusEnum.PARAMETER_ERROR,bindingResult.getFieldErrors().get(0).getDefaultMessage());
    }
}
